﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using YouTubeAccessLayer;
using System.Reflection;
using System.IO;

using DatabaseLayer;
using System.ServiceProcess;
using System.Threading;
using System.Diagnostics;
using FacebookAccessLayer;

namespace IVRJunctionUI
{
    public partial class Configuration : System.Web.UI.Page
    {

        private String IVRJunctionFolderLocation;
        private bool isModerationOnline;
        private bool isSynchronizeBranch;
        private bool isFacebookConfigure;

        protected void Page_Load(object sender, EventArgs e)
        {

            DatabaseFunctions objectDatabaseFunctions = new DatabaseFunctions();

            // first item of tuple is isModerationOnline, second item of tuple is isSynchronizeBranches
            var tempTuple = objectDatabaseFunctions.getIVRJunctionConfiguration();

            // this will be executed if there is some database error
            if (tempTuple != null)
            {
                var genericConfigurationTuple = tempTuple.Item6;

                isModerationOnline = genericConfigurationTuple.Item1;
                isSynchronizeBranch = genericConfigurationTuple.Item2;
                isFacebookConfigure = genericConfigurationTuple.Item3;


                // this will be set if the branch is set in the database
                if (tempTuple.Item1 != null)
                {

                    // Set the Branch Data
                    TextBoxBranchName.Text = tempTuple.Item1;
                    ImageTickBranchPanel.Visible = true;
                    PanelBranch.Enabled = false;


                    // Set the IVR Folderlocation data
                    TextBoxIVRFolderLocation.Text = tempTuple.Item2;
                    IVRJunctionFolderLocation = tempTuple.Item2;
                    ImageTickIVRFolderLocationPanel.Visible = true;
                    PanelIVRFolderLocation.Enabled = false;

                    ButtonSubmit.Enabled = false;

                }

                // this implies if the moderation is offline
                if (!isModerationOnline)
                {
                    PanelDropBoxConfiguration.Visible = false;
                    PanelYTChannelInformation.Visible = false;
                    PanelVideoProperties.Visible = false;


                }
                // if moderation is online
                else
                {
                    PanelDropBoxConfiguration.Visible = isSynchronizeBranch;
                    CustomValidatorDropBoxFolder.Enabled = true;


                    if (tempTuple.Item1 != null)
                    {
                        // this is to make sure that the value of YTVideo Information Textboxes are not overridden by db value
                        // when we want to edit them
                        if (Session["count"] == null)
                        {
                            Session["count"] = 0;
                        }

                        // make the Panel for controlling service visible
                        PanelServiceControlPanel.Visible = true;
                        setValuesForServiceControlPanel();

                        // Panel will be visible if we need to configure facebook else it will not
                        PanelFacebookConfiguration.Visible = isFacebookConfigure;
                        HyperLinkFB.NavigateUrl = getFacebookAccessTokenURL();
                        // load the data into the form
                        // and set the pictures on


                        // Set the DropBox Data
                        String dropBoxFolderLocation = tempTuple.Item5;
                       
                        // fill one text box
                        TextBoxDropBoxFolderLocation.Text = dropBoxFolderLocation;
                        // enable tick mark
                        ImageTickDropBoxFolderPanel.Visible = true;


                        // disbale the DropBox Panel
                        PanelDropBoxConfiguration.Enabled = false;

                        // Set the YouTube Table

                        var youTubeConfigurationTuple = tempTuple.Item3;
                        TextBoxYTDeveloperKey.Text = youTubeConfigurationTuple.Item1;
                        TextBoxYTAccountName.Text = youTubeConfigurationTuple.Item2;
                        TextBoxYTUsername.Text = youTubeConfigurationTuple.Item3;
                        TextBoxYTPassword.Text = youTubeConfigurationTuple.Item4;

                        PanelYTChannelInformation.Enabled = false;
                        ImageTickYouTubeConfigPanel.Visible = true;


                        // when session variable count is 0 then only override the YT video information textbox values with Db values 
                        if ((Int32)Session["count"] == 0)
                        {
                            var youTubeVideoInformationTuple = tempTuple.Item4;
                            TextBoxVideoTitle.Text = youTubeVideoInformationTuple.Item1;
                            TextBoxVideoKeywords.Text = youTubeVideoInformationTuple.Item2;
                            TextBoxVideoDescription.Text = youTubeVideoInformationTuple.Item3;
                            TextBoxVideoLocation.Text = youTubeVideoInformationTuple.Item4;

                            LabelVideoTitle.Text = youTubeVideoInformationTuple.Item1;
                            LabelVideoKeywords.Text = youTubeVideoInformationTuple.Item2;
                            LabelVideoDescription.Text = youTubeVideoInformationTuple.Item3;
                            LabelVideoLocation.Text = youTubeVideoInformationTuple.Item4;

                            //changeStateOfVideoProperties(true);
                            //ImageTickYTVideoInformation.Visible = true;
                        }


                        //PanelVideoProperties.Enabled = false;
                        changeStateOfVideoProperties(false);
                        ButtonEdit.Visible = true;


                        ButtonSubmit.Enabled = false;

                    }
                }
            }

        }

        private void setValuesForServiceControlPanel()
        {
            ServiceController objectServiceController = new ServiceController("IVR Junction- YouTube Upload Service");
            try
            {
                LabelYouTubeServiceStatus.Text = objectServiceController.Status.ToString();
                if (objectServiceController.Status == ServiceControllerStatus.Stopped)
                {
                    ButtonYouTubeService.Text = "Start";
                }
                else if (objectServiceController.Status == ServiceControllerStatus.Running)
                {
                    ButtonYouTubeService.Text = "Stop";

                }
                else
                {
                    ButtonYouTubeService.Text = "Control Button";
                    ButtonYouTubeService.Enabled = false;
                }
            }
            catch (Exception generalException)
            {
                // log this event
                Console.WriteLine(generalException.Message);
                LabelYouTubeServiceStatus.Text = "Not installed";
                //ButtonYouTubeService.Text = "Install";
                ButtonYouTubeService.Enabled= false;

            }


            if (isSynchronizeBranch)
            {


                TableRowModerationService2.Visible = true;
                TableRowSynchronizationService2.Visible = true;
                objectServiceController = new ServiceController("IVR Junction- Moderation Service");
                try
                {
                    LabelModerationService2.Text = objectServiceController.Status.ToString();
                    if (objectServiceController.Status == ServiceControllerStatus.Stopped)
                    {
                        ButtonModerationService2.Text = "Start";
                    }
                    else if (objectServiceController.Status == ServiceControllerStatus.Running)
                    {
                        ButtonModerationService2.Text = "Stop";

                    }
                    else
                    {
                        ButtonModerationService2.Text = "Control Button";
                        ButtonModerationService2.Enabled = false;
                    }
                }
                catch (Exception generalException)
                {
                    // log this event
                    Console.WriteLine(generalException.Message);
                    LabelModerationService2.Text = "Not installed";
                    //ButtonModerationService2.Text = "Install";
                    ButtonModerationService2.Enabled = false;

                }

                objectServiceController = new ServiceController("IVR Junction- Synchronization Service");
                try
                {
                    LabelSynchronizationService2.Text = objectServiceController.Status.ToString();
                    if (objectServiceController.Status == ServiceControllerStatus.Stopped)
                    {
                        ButtonSynchronizationService2.Text = "Start";
                    }
                    else if (objectServiceController.Status == ServiceControllerStatus.Running)
                    {
                        ButtonSynchronizationService2.Text = "Stop";

                    }
                    else
                    {
                        ButtonSynchronizationService2.Text = "Control Button";
                        ButtonSynchronizationService2.Enabled = false;
                    }
                }
                catch (Exception generalException)
                {
                    // log this event
                    Console.WriteLine(generalException.Message);
                    LabelSynchronizationService2.Text = "Not installed";
                    //ButtonSynchronizationService2.Text = "Install";
                    ButtonSynchronizationService2.Enabled = false;

                }

            }
            else
            {
                // install only service 2 as Synchronization of branches is not necessary

                TableRowModerationService2.Visible = true;

                objectServiceController = new ServiceController("IVR Junction- Moderation Service");
                try
                {
                    LabelModerationService2.Text = objectServiceController.Status.ToString();
                    if (objectServiceController.Status == ServiceControllerStatus.Stopped)
                    {
                        ButtonModerationService2.Text = "Start";
                    }
                    else if (objectServiceController.Status == ServiceControllerStatus.Running)
                    {
                        ButtonModerationService2.Text = "Stop";

                    }
                    else
                    {
                        ButtonModerationService2.Text = "Control Button";
                        ButtonModerationService2.Enabled = false;
                    }
                }
                catch (Exception generalException)
                {
                    // log this event
                    Console.WriteLine(generalException.Message);
                    //LabelModerationService2.Text = "Not installed";
                    //ButtonModerationService2.Text = "Install";
                    //ButtonModerationService1.Enabled = false;

                }
            }



        }

        protected void ButtonYouTubeService_Click(object sender, EventArgs e)
        {
            ServiceController objectServiceController = new ServiceController("IVR Junction- YouTube Upload Service");
            try
            {
                if (objectServiceController.Status == ServiceControllerStatus.Stopped)
                {
                    objectServiceController.Start();
                    //Thread newThread = new Thread(objectServiceController.Start);
                    //newThread.Start();
                }
                else if (objectServiceController.Status == ServiceControllerStatus.Running)
                {
                    objectServiceController.Stop();
                    //Thread newThread = new Thread(objectServiceController.Stop);
                    //newThread.Start();

                }

            }
            catch (Exception generalException)
            {
                // log this event
                Console.WriteLine(generalException.Message);

            }
            Thread.Sleep(10000);


            //setValuesForServiceControlPanel();
            Page.Response.Redirect(Page.Request.Url.ToString(), true);
        }





        protected void ButtonModerationService2_Click(object sender, EventArgs e)
        {


            ServiceController objectServiceController = new ServiceController("IVR Junction- Moderation Service");
            try
            {
                if (objectServiceController.Status == ServiceControllerStatus.Stopped)
                {
                    objectServiceController.Start();
                    //Thread newThread = new Thread(objectServiceController.Start);
                    //newThread.Start();
                }
                else if (objectServiceController.Status == ServiceControllerStatus.Running)
                {
                    objectServiceController.Stop();
                    //Thread newThread = new Thread(objectServiceController.Stop);
                    //newThread.Start();

                }

            }
            catch (Exception generalException)
            {
                // log this event
                Console.WriteLine(generalException.Message);

            }
            Thread.Sleep(10000);


            //setValuesForServiceControlPanel();
            Page.Response.Redirect(Page.Request.Url.ToString(), true);
        }

        protected void ButtonSynchronizationService2_Click(object sender, EventArgs e)
        {


            ServiceController objectServiceController = new ServiceController("IVR Junction- Synchronization Service");
            try
            {
                if (objectServiceController.Status == ServiceControllerStatus.Stopped)
                {
                    objectServiceController.Start();
                    //Thread newThread = new Thread(objectServiceController.Start);
                    //newThread.Start();
                }
                else if (objectServiceController.Status == ServiceControllerStatus.Running)
                {
                    objectServiceController.Stop();
                    //Thread newThread = new Thread(objectServiceController.Stop);
                    //newThread.Start();

                }

            }
            catch (Exception generalException)
            {
                // log this event
                Console.WriteLine(generalException.Message);

            }
            Thread.Sleep(10000);


            //setValuesForServiceControlPanel();
            Page.Response.Redirect(Page.Request.Url.ToString(), true);
        }

        private void changeStateOfVideoProperties(bool value)
        {
            FileUploadBackgroundImage.Enabled = value;
            TableCellBackgroundImage.Visible = value;

            TextBoxVideoTitle.Visible = value;
            LabelVideoTitle.Visible = !value;
            TableCellVideoTitle.Visible = value;

            TextBoxVideoDescription.Visible = value;
            LabelVideoDescription.Visible = !value;
            TableCellVideoDescription.Visible = value;

            TextBoxVideoKeywords.Visible = value;
            LabelVideoKeywords.Visible = !value;
            TableCellVideoKeywords.Visible = value;

            TextBoxVideoLocation.Visible = value;
            LabelVideoLocation.Visible = !value;
            TableCellVideoLocation.Visible = value;

            ImageTickYTVideoInformation.Visible = !value;
            ImageFromDB.Visible = !value;
        }


        protected void ButtonEdit_Click(object sender, EventArgs e)
        {
            changeStateOfVideoProperties(true);
            ButtonEdit.Visible = false;
            ButtonSave.Visible = true;
            //flagToDifferentiate = 1;
            // This is set to make sure that now textbox values will not be overridden by DB values in PageLoad event
            Session["count"] = 1;

        }

        protected void ButtonSave_Click(object sender, EventArgs e)
        {

            if (FileUploadBackgroundImage.HasFile)
                CustomValidatorFileUpload.Validate();
            else
                CustomValidatorFileUpload.IsValid = true;

            RequiredFieldValidatorVideoTitle.Validate();
            RequiredFieldValidatorVideoKeywords.Validate();
            RequiredFieldValidatorVideoDescritpion.Validate();
            RequiredFieldValidatorVideoLocation.Validate();

            if (CustomValidatorFileUpload.IsValid && RequiredFieldValidatorVideoTitle.IsValid && RequiredFieldValidatorVideoKeywords.IsValid
                && RequiredFieldValidatorVideoDescritpion.IsValid && RequiredFieldValidatorVideoLocation.IsValid)
            {
                // save the data in the database
                bool isSuccess = false;
                try
                {
                    if (FileUploadBackgroundImage.HasFile)
                    {
                        HttpPostedFile file = FileUploadBackgroundImage.PostedFile;
                        file.SaveAs(IVRJunctionFolderLocation + "\\backgroundImage.jpg");

                        file.SaveAs(Server.MapPath("~/Resource") + "\\backgroundImage.jpg");
                    }
                    DatabaseFunctions objectDatabaseFunctions = new DatabaseFunctions();
                    isSuccess = objectDatabaseFunctions.updateVideoPropertiesInConfigurationTable(TextBoxVideoTitle.Text,
                        TextBoxVideoKeywords.Text, TextBoxVideoDescription.Text, TextBoxVideoLocation.Text);


                }
                catch (Exception generalException)
                {
                    // this should be logged in an event logger
                    Console.WriteLine(generalException.Message);
                }

                if (isSuccess)
                {
                    ButtonSave.Visible = false;
                    ButtonEdit.Visible = true;
                    changeStateOfVideoProperties(false);

                    //flagToDifferentiate = 0;
                    // This is set to make sure that now textbox values should be overridden by DB values in PageLoad event
                    Session["count"] = 0;
                    Page.Response.Redirect(Page.Request.Url.ToString(), true);
                }
                else
                {
                    changeStateOfVideoProperties(true);
                    ButtonEdit.Visible = false;
                }

            }
            else
            {
                changeStateOfVideoProperties(true);
                ButtonEdit.Visible = false;
            }

            //setValuesForServiceControlPanel();

        }

        protected void ButtonReset_Click(object sender, EventArgs e)
        {
            DatabaseFunctions objectDatabaseFunctions = new DatabaseFunctions();
            bool isDeletionSuccess = objectDatabaseFunctions.deleteIVRJunctionConfiguration();
            if (isDeletionSuccess)
            {
                Response.Redirect("~/ConfigureOptions.aspx");
            }
        }
        protected void ButtonSubmit_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                try
                {
                    IVRJunctionFolderLocation = TextBoxIVRFolderLocation.Text;
                    if (!System.IO.Directory.Exists(IVRJunctionFolderLocation))
                    {
                        System.IO.DirectoryInfo directory = System.IO.Directory.CreateDirectory(IVRJunctionFolderLocation);
                    }

                    if (isModerationOnline)
                    {
                        HttpPostedFile file = FileUploadBackgroundImage.PostedFile;

                        file.SaveAs(IVRJunctionFolderLocation + "\\backgroundImage.jpg");
                        file.SaveAs(Server.MapPath("~/Resource") + "\\backgroundImage.jpg");
                    }
                    //TextBoxYTVideoLocation.Text=TextBoxYTVideoLocation+"\\TestVideoFile.wmv";
                    // code to write the values in databases
                    // write all the values in the database
                    DatabaseFunctions objectDatabaseFunctions = new DatabaseFunctions();
                    objectDatabaseFunctions.insertOrUpdateIVRJunctionConfigurationTable(TextBoxBranchName.Text, IVRJunctionFolderLocation, TextBoxYTDeveloperKey.Text,
                        TextBoxYTAccountName.Text, TextBoxYTUsername.Text, TextBoxYTPassword.Text, TextBoxVideoTitle.Text, TextBoxVideoKeywords.Text, TextBoxVideoDescription.Text,
                        TextBoxVideoLocation.Text, TextBoxDropBoxFolderLocation.Text);

                }
                catch (Exception generalException)
                {
                    // this event should be written to content logger
                    Console.WriteLine(generalException.Message);
                }



                //Page_Load(sender,e);
                Page.Response.Redirect(Page.Request.Url.ToString(), true);
            }
        }

        protected void DropBoxFolderValidator(object sender, ServerValidateEventArgs e)
        {
            try
            {

                if (e.Value == null || e.Value.Trim() == null || e.Value.Trim() == "")
                {
                    e.IsValid = false;

                }
                else if (!System.IO.Directory.Exists(e.Value))
                {
                    e.IsValid = false;

                }
                else
                    e.IsValid = true;
            }
            catch (Exception)
            {
                e.IsValid = false;
            }


        }

        protected void IVRFolderValidator(object sender, ServerValidateEventArgs e)
        {
            try
            {

                if (e.Value == null || e.Value.Trim() == null || e.Value.Trim() == "")
                {
                    e.IsValid = false;

                }
                else if (!System.IO.Directory.Exists(e.Value))
                {
                    try
                    {
                        System.IO.DirectoryInfo directory = System.IO.Directory.CreateDirectory(IVRJunctionFolderLocation);
                        e.IsValid = true;
                    }
                    catch (Exception)
                    {
                        e.IsValid = false;
                    }

                }
                else
                    e.IsValid = true;
            }
            catch (Exception)
            {
                e.IsValid = false;
            }


        }



        // This is a validator function to validate the YouTube Channel Information uploaded by user
        protected void YouTubeChannelInformationValidation(object sender, ServerValidateEventArgs e)
        {

            //string executableLocation = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            //string _codeBaseFolder = this.GetType().Assembly.CodeBase;
            string mapPath = Server.MapPath("Resource\\");
            string videoLocation = Path.Combine(mapPath, "TestVideoFile.avi");

            YouTubeFunctions objectYouTubeFunctions = new YouTubeFunctions(TextBoxYTDeveloperKey.Text,
                TextBoxYTAccountName.Text, TextBoxYTUsername.Text, TextBoxYTPassword.Text);

            int statusCode = objectYouTubeFunctions.UploadVideoOnYouTube(videoLocation, "Test Upload", "Test, No Branch, Local News, NGO, IVR System", "Test Description", "Bangalore, India");

            if (statusCode == 2)
                e.IsValid = true;
            else
                e.IsValid = false;

        }


        //This function validates the file format and file path for output YouTube video file location
        // This function is now unsed, hence, this can be deleted
        protected void OutputVideoFileValidation(object sender, ServerValidateEventArgs e)
        {
            //FileUploadBackgroundImage.PostedFile.FileName
            try
            {

                if (e.Value == null || e.Value.Trim() == null || e.Value.Trim() == "")
                {
                    e.IsValid = false;

                }
                else if (System.IO.Directory.Exists(Path.GetDirectoryName(e.Value)) &&
                    Path.GetExtension(e.Value).Equals(".wmv", StringComparison.OrdinalIgnoreCase))
                    e.IsValid = true;
                else
                    e.IsValid = false;
            }
            catch (Exception)
            {
                e.IsValid = false;
            }
        }

        //This function validates the FileUploadBackgroundImage
        protected void FileUploadBackgroundImageValidation(object sender, ServerValidateEventArgs e)
        {
            //FileUploadBackgroundImage.PostedFile.FileName
            try
            {

                if (FileUploadBackgroundImage.HasFile)
                {
                    String extension = Path.GetExtension(FileUploadBackgroundImage.PostedFile.FileName);
                    if (extension.Equals(".jpeg", StringComparison.OrdinalIgnoreCase) ||
                        extension.Equals(".jpg", StringComparison.OrdinalIgnoreCase))
                        e.IsValid = true;
                    else
                        e.IsValid = false;
                }
                else
                    e.IsValid = false;
            }
            catch (Exception)
            {
                e.IsValid = false;
            }
        }

        protected String getFacebookAccessTokenURL()
        {
            FacebookFunctions objectFacebookFunctions = new FacebookFunctions();
            var facebookConfigurations = objectFacebookFunctions.getFacebookConfigurations();
            Uri uri = objectFacebookFunctions.getAccessTokenFromOAuth("336508236381580", "c4c5fb6554ca06e143cc7cfc11163f7c", "http://localhost/IVRJunctionUI/FacebookAccessToken.aspx");
            return uri.ToString();
        }

    }
}